﻿
using YAWD.Data;
using System.Windows;
using System.IO;
using System;
using YAWD.Utils;
namespace YAWD.BL.Services
{
    static class DatabaseServices
    {
        private static bool BackupDb(string strConnectionString)
        {
            try
            {
                if (string.IsNullOrEmpty(strConnectionString))
                    return false;

                string strFilePath = strConnectionString.Replace(@"data source=""", "");
                strFilePath = strFilePath.Replace('"', ' ').Trim();
                string strPath = strFilePath.Substring(0, strFilePath.LastIndexOf(Path.DirectorySeparatorChar)).Trim();

                strPath = Path.Combine(Environment.CurrentDirectory, strPath);
                strPath = Path.GetFullPath(strPath);

                if (Directory.Exists(strPath + "Backup") == false)
                    Directory.CreateDirectory(strPath + "Backup");

                File.Copy(strFilePath, strPath + @"Backup\dbBackup_" + DateTime.Now.ToFileTime() + ".bck", true);

                return true;
            }
            catch (Exception ex)
            {
                Util.LogException(ex, strConnectionString);
                return false;
            }
        }

        public static int GetCount()
        {
            return Dal.GetInstance.GetLaunch();
        }
        public static bool GetDonate()
        {
            return Dal.GetInstance.GetDonate();
        }
        public static string GetIp()
        {
            return Dal.GetInstance.GetIp();
        }
        public static void UpdateCount(int count)
        {
            Dal.GetInstance.UpdateCount(count);
        }
        public static void UpdateDonate()
        {
            Dal.GetInstance.UpdateDonate();
        }
        public static int? Upgrade()
        {
            Dal objDal = Dal.GetInstance;

            string strVersion = objDal.GetDbVersion();

            if (strVersion == "1") return null;

            bool backupSucess = BackupDb(Dal.ConnectionString);

            if (backupSucess == false)
            {
                MessageBoxResult bContinue =
                    MessageBox.Show(
                        ((App)Application.Current).LoadedLanguageResourceDictionary["BackupErrorMessageConfirmation"].
                            ToString(),
                        "YAWD", MessageBoxButton.YesNo);
                if (bContinue == MessageBoxResult.No)
                    return null;
            }

            if (strVersion == null)
            {
                objDal.CreateConfigurationTable();
                objDal.UpgradeDb0To1();
                return 1;
            }
            return null;
        }

    }
}
